package com.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class ShardHashUtils {
    private static Logger logger = LoggerFactory.getLogger(ShardHashUtils.class);

    public ShardHashUtils() {
    }

    public static int getShardNo(String shardKey, int shardSize) {
        if (StringUtils.isEmpty(shardKey)) {
            throw new IllegalArgumentException("shardKey cannot be empty");
        } else if (shardSize < 1) {
            throw new IllegalArgumentException("shardSize must be greater than 1");
        } else {
            int hashCode = Math.abs(hash(shardKey));
            int shardNo = hashCode % shardSize;
            logger.info("shardKey:" + shardKey + ",shardSize:" + shardSize + ",shardNo:" + shardNo);
            return shardNo + 1;
        }
    }

    private static int hash(Object key) {
        int h;
        return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
    }
}